package com.wolfden.drugserver.spawning;

import java.io.IOException;
import java.util.HashMap;

import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;

import com.wolfden.drugserver.utils.FileUtils;
import com.wolfden.drugserver.warping.SerializableLocation;

public class SpawnMap {

	private HashMap<String, SerializableLocation> spawnMap;
	private Plugin plugin;
	
	public SpawnMap(Plugin p) {
		this.plugin = p;
	}
	
	public void save() {
		try {
			FileUtils.save("spawns.bin", this.spawnMap);
		} catch (IOException e) {
			plugin.getLogger().info("Could not save spawns.bin");
		}
	}
	
	@SuppressWarnings("unchecked")
	public void load() {
		try {
			this.spawnMap = (HashMap<String, SerializableLocation>) FileUtils.load("spawns.bin");
		} catch (IOException e) {
			plugin.getLogger().info("spawns.bin could not be loaded, creating new SpawnMap.");
			this.spawnMap = new HashMap<String, SerializableLocation>();
		}
	}
	
	public void changeSpawn(Player p) {
		this.changeSpawn(p.getName().toLowerCase(), new SerializableLocation(p.getLocation()));
	}
	
	private void changeSpawn(String playerName, SerializableLocation loc) {
		this.spawnMap.put(playerName, loc);
	}
	
	public Location getSpawnForPlayer(Player p) {
		return this.getSpawnForPlayer(p.getName().toLowerCase());
	}
	
	private Location getSpawnForPlayer(String playerName) {
		return this.spawnMap.get(playerName.toLowerCase()).getLocation(plugin.getServer());
	}
	
	public boolean containsPlayer(Player p) {
		return this.containsPlayer(p.getName().toLowerCase());
	}
	
	private boolean containsPlayer(String playerName) {
		return (this.spawnMap.containsKey(playerName));
	}
}
